﻿"""
Definition of views.
"""

from django.shortcuts import render
from django.http import HttpRequest,HttpResponse,HttpResponseRedirect,JsonResponse
from django.views.decorators.csrf import csrf_protect, csrf_exempt
from django.utils import timezone
from django.core import serializers
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

from django.conf import settings
from django.core.mail import send_mass_mail
from django.core.mail import send_mail
from django.http import StreamingHttpResponse 

from .models import Message
from .models import Vacation
from .models import User
from .models import Expense
from .models import ExpenseItem

from django.template import RequestContext
from datetime import datetime
from django.contrib.auth.hashers import make_password, check_password
from django.db.models import Sum
import json
import simplejson
import sys
import uuid

default_encoding = 'utf-8'
if sys.getdefaultencoding() != default_encoding:
    reload(sys)  
    sys.setdefaultencoding(default_encoding)

def expense(request):
    #context={"messages":Message.objects.order_by('-publish_date')}
    #return render(request,'lxoa/user.html')
    username=request.session.get('username')
    if username :
      return render(request,'lxoa/expense.html')
    else :
      return render(request,'lxoa/login.html')

def expenseapprove(request):
    #context={"messages":Message.objects.order_by('-publish_date')}
    #return render(request,'lxoa/user.html')
    userdep=request.session.get('userdepartment')
    username=request.session.get('username')
    if username and int(userdep)==settings.ADMIN_USER_ID:
      return render(request,'lxoa/expenseapprove.html')
    else :
      return render(request,'lxoa/login.html')

def expensestatistics(request):
    #context={"messages":Message.objects.order_by('-publish_date')}
    #return render(request,'lxoa/user.html')
    userdep=request.session.get('userdepartment')
    username=request.session.get('username')
    if username and int(userdep)==settings.ADMIN_USER_ID:
      return render(request,'lxoa/expensestatistics.html')
    else :
      return render(request,'lxoa/login.html')

  

@csrf_exempt
def saveexpense2(request):
  expense_typeb = request.POST.get('expense_typeb','')
  expense_Approver = request.POST.get('expense_Approver','')
  txt_total = request.POST.get('txt_total','')
  txt_date = request.POST.get('txt_date','')
  expense_remark = request.POST.get('expense_remark','')  
  itmes = request.POST.get('itmes','')
  req=simplejson.loads(request.body)

  #utype =0 #0 general user 1 admin user
  #uregdate =timezone.now()
  #temps=request.POST.get('temp','')
  #remarks =''
  if expense_typeb and expense_Approver and txt_total:
   #obj = User(username=uname,useremail=umail,usertype=utype,userdepartment=udept,userpwd=upwdjm,userresume=uresume,regdate=uregdate,entrydate=entdate,temp=temps,remark=remarks)
   #obj.save()
   #dj_ps = make_password(ps, None, 'pbkdf2_sha256')   #创建django密码， 第二个参数为None是每次产生的密码都不用，第三个参数为算法， 后面两个参数可以忽略
   #ps_bool = check_password(ps, dj_ps) # check_password 返回值为一个Bool类型，验证密码的正确与否
   context={'success':'1','error':'0'}
   return HttpResponse(json.dumps(context), content_type='application/json')
  else :
     context={'success':'0','error':'1'}
     return JsonResponse(context)

@csrf_exempt
def saveexpense(request):
  req=simplejson.loads(request.body)
  temps=''
  #req['expense_Approver_email'] 审批人邮箱
  applydates=timezone.now()
  uuids=uuid.uuid1()
  if req['expense_typeb'] and req['expense_Approver'] and req['txt_total'] and req['datas'] and req['op']:
     if req['op']=='add':
        obj = Expense(title=req['expense_typeb'],applyuser=req['applyuser'],applydate=req['txt_date'],happenoffice='',approvalstatus=0,approvaluser=req['expense_Approver']+'$'+req['expense_Approver_email'],approvaldate='',totalprice=req['txt_total'],guid=uuids,temp=request.session.get('useremail'),remark=req['expense_remark'])
        obj.save()
        for asset in req['datas']:
           ExpenseItem(itmetitle='',expensetype=asset['types'],expenseprice=asset['price'],temp=asset['price'],expenseguid=uuids,remark=asset['desc']).save()
        context={'success':'1','error':'0'}
        return HttpResponse(json.dumps(context), content_type='application/json')
     else :
       ids=req['guid']
       Expense.objects.filter(guid=ids).delete()
       ExpenseItem.objects.filter(expenseguid=ids).delete()
       obj = Expense(title=req['expense_typeb'],applyuser=req['applyuser'],applydate=req['txt_date'],happenoffice='',approvalstatus=0,approvaluser=req['expense_Approver']+'$'+req['expense_Approver_email'],approvaldate='',totalprice=req['txt_total'],guid=uuids,temp=request.session.get('useremail'),remark=req['expense_remark'])
       obj.save()
       for asset in req['datas']:
         ExpenseItem(itmetitle='',expensetype=asset['types'],expenseprice=asset['price'],temp=asset['price'],expenseguid=uuids,remark=asset['desc']).save()
       context={'success':'1','error':'0'}
       return HttpResponse(json.dumps(context), content_type='application/json')
  else :
     context={'success':'0','error':'1'}
     return JsonResponse(context)

@csrf_exempt
def delexpense(request):
  ids = request.POST.get('id','')
  if id:
   Expense.objects.filter(guid=ids).delete()
   ExpenseItem.objects.filter(expenseguid=ids).delete()
   context={'success':'1','error':'0'}
   return HttpResponse(json.dumps(context), content_type='application/json')
  else :
     context={'success':'0','error':'1'}
     return JsonResponse(context)

@csrf_exempt
def updateexpense(request):
  req=simplejson.loads(request.body)
  if req['guid'] and req['type']:
   Expense.objects.filter(guid=req['guid']).update(approvalstatus=req['type'],approvaldate=timezone.now(),happenoffice=req['commons'])
   context={'success':'1','error':'0'}
   return HttpResponse(json.dumps(context), content_type='application/json')
  else :
   context={'success':'0','error':'1'}
   return JsonResponse(context)

@csrf_exempt
def userlogin(request):
  uname = request.POST.get('username','')
  upwd = request.POST.get('userpwd','')
  if uname and upwd:
   data_set = []
   #user=len(User.objects.filter(useremail=uname,userpwd=pwdjm))
   #user=User.objects.filter(username=uname,userpwd=upwd)
   #"id":asset["id"],"username":asset["username"],"useremail":asset["useremail"],"usertype":asset["usertype"],"userdepartment":asset["userdepartment"],"userpwd":asset["userpwd"],"userresume":asset["userresume"],"regdate":asset["regdate"],"entrydate":asset["entrydate"],"temp":asset["temp"],"remark":asset["remark"]
   upwdjm=make_password(upwd,'mao', 'pbkdf2_sha256')
   user=User.objects.filter(useremail=uname,userpwd=upwdjm)
   if user and user[0]:
          request.session['userdepartment']=user[0].userdepartment
          request.session['username']=user[0].username
          request.session['useremail']=user[0].useremail
          context={'success':'1','error':'0'}
          #context={'success':'1','error':'0',"id":user[0].id,"username":user[0].username}
          return JsonResponse(context)
   else:
          context={'success':'0','error':'1'}
          return JsonResponse(context)

@csrf_exempt
def username(request):
  username=request.session.get('username')
  userdep=request.session.get('userdepartment')
  admins=0
  if int(userdep)==settings.ADMIN_USER_ID :
    admins=1
  if username:
       context={'success':'1','error':'0','uname':username,'admin':admins}
       #context={'success':'1','error':'0',"id":user[0].id,"username":user[0].username}
       return JsonResponse(context)
  else:
       context={'success':'0','error':'1'}
       return JsonResponse(context)
@csrf_exempt
def userlogout(request):
    try:
     del request.session['userdepartment']
     del request.session['username']
     del request.session['useremail']
     context={'success':'1','error':'0'}
     return JsonResponse(context)
    except Exception:
       context={'success':'0','error':'1'}
       return JsonResponse(context)

@csrf_exempt
def upload_ajax(request):
    if request.method == 'POST':
        file_obj = request.FILES.get('file')
        import os
        time = timezone.localtime(timezone.now()).strftime("%Y%m%d%H%M%S")
        time=time+os.path.splitext(file_obj.name)[1]
        f = open(os.path.join(settings.BASE_DIR, 'lxoa', 'doc',time),'wb')
        for chunk in file_obj.chunks():
            f.write(chunk)
        f.close()
        context={'success':'1','error':'0','newfilename':time}
        return JsonResponse(context)
def file_download(request):
    file_obj = request.GET.get('filename')
    with open(settings.BASE_DIR+'/lxoa/doc/'+file_obj,encoding='gb18030', errors='ignore') as f:
        c = f.read()
    return HttpResponse(c)

def file_down(request):
    file_obj = request.GET.get('filename')
    file=open(settings.BASE_DIR+'/lxoa/doc/'+file_obj,'rb')  
    response =HttpResponse(file)  
    response['Content-Type']='application/octet-stream'  
    response['Content-Disposition']='attachment;filename='+file_obj
    return response

def list(request):
    json_data = serializers.serialize("json", Message.objects.all(),ensure_ascii = False)
    return HttpResponse(json_data,content_type="application/json")
 
def getuserlist(request):
    userlist=settings.USER_LIST
    return HttpResponse(json.dumps(userlist),content_type='application/json')

def page(deploy_list ,limit,offset):
    try:
        paginator = Paginator(deploy_list, limit)
    except Exception:
        return {"data":'none',"response_data":'none'}
    page = int(int(offset) / int(limit) + 1)
    data=paginator.page(page)
    response_data = {'total': deploy_list.count(), 'rows': []}
    return {"data":data,"response_data":response_data}

def listmyexpense(request):
    data_set = []
    data_sets = []
    username=request.session.get('username')
    useremail=request.session.get('useremail')
    if username and useremail:
      length = len(Expense.objects.filter(applyuser=username,temp=useremail).all())
      paginator = Paginator(Expense.objects.filter(applyuser=username,temp=useremail).all().order_by("-id").values(), 100)
      page = int(int(0) / int(1) + 1)
      data=paginator.page(page)
      for asset in data:
        data_set.append({ "id":asset["id"],"title":asset["title"],"applyuser":asset["applyuser"],"applydate":asset["applydate"],"happenoffice":asset["happenoffice"],"approvalstatus":asset["approvalstatus"],"approvaluser":asset["approvaluser"],"approvaldate":asset["approvaldate"],"totalprice":asset["totalprice"],"guid":asset["guid"],"temp":asset["temp"],"remark":asset["remark"]})
      return HttpResponse(json.dumps({'rows':data_set,'total':length}),content_type='application/json')
    else :
        return HttpResponse(json.dumps({'rows':-1,'total':-1,'role':-1}),content_type='application/json')

@csrf_exempt
def getlistbyid(request):
    data_set = []
    data_sets = []
    username=request.session.get('username')
    useremail=request.session.get('useremail')
    id = request.POST.get('id')
    guid=''
    json_data=''
    if username and useremail and id:
      data = Expense.objects.filter(guid=id).all().order_by("-id").values()
      #data = Expense.objects.filter(applyuser=username,temp=useremail,guid=id).all().order_by("-id").values()
      for asset in data:
        guid=asset["guid"]
        json_data = serializers.serialize("json", ExpenseItem.objects.filter(expenseguid=guid).all(),ensure_ascii = False)
        data_set.append({ "id":asset["id"],"title":asset["title"],"applyuser":asset["applyuser"],"applydate":asset["applydate"],"happenoffice":asset["happenoffice"],"approvalstatus":asset["approvalstatus"],"approvaluser":asset["approvaluser"],"approvaldate":asset["approvaldate"],"totalprice":asset["totalprice"],"guid":asset["guid"],"temp":asset["temp"],"remark":asset["remark"],"item":json_data})
      return HttpResponse(json.dumps({'rows':data_set}),content_type='application/json')
      #return HttpResponse(json.dumps({'rows':1,'total':1,'role':guid}),content_type='application/json')
    else :
        return HttpResponse(json.dumps({'rows':-1,'total':-1,'role':-1}),content_type='application/json')
def listapproveexpense(request):
    data_set = []
    username=request.session.get('username')
    useremail=request.session.get('useremail')
    userdep=request.session.get('userdepartment')
    if username and useremail and int(userdep)==settings.ADMIN_USER_ID:
      length = len(Expense.objects.filter(approvalstatus=0,approvaluser=username+'$'+useremail).all())
      paginator = Paginator(Expense.objects.filter(approvalstatus=0,approvaluser=username+'$'+useremail).all().order_by("-id").values(), 1000)
      page = int(int(0) / int(1) + 1)
      data=paginator.page(page)
      for asset in data:
        data_set.append({ "id":asset["id"],"title":asset["title"],"applyuser":asset["applyuser"],"applydate":asset["applydate"],"happenoffice":asset["happenoffice"],"approvalstatus":asset["approvalstatus"],"approvaluser":asset["approvaluser"],"approvaldate":asset["approvaldate"],"totalprice":asset["totalprice"],"guid":asset["guid"],"temp":asset["temp"],"remark":asset["remark"]})
      return HttpResponse(json.dumps({'rows':data_set,'total':length}),content_type='application/json')
    else :
        return HttpResponse(json.dumps({'rows':-1,'total':-1,'role':-1}),content_type='application/json')

def expensestatisticslist(request):
    data_set = []
    username=request.session.get('username')
    useremail=request.session.get('useremail')
    userdep=request.session.get('userdepartment')
    if username and useremail and int(userdep)==settings.ADMIN_USER_ID:
      length = len(Expense.objects.filter(approvalstatus=1).all())
      paginator = Paginator(Expense.objects.filter(approvalstatus=1).all().order_by("-id").values(), 1000)
      page = int(int(0) / int(1) + 1)
      data=paginator.page(page)
      for asset in data:
        data_set.append({ "id":asset["id"],"title":asset["title"],"applyuser":asset["applyuser"],"applydate":asset["applydate"],"happenoffice":asset["happenoffice"],"approvalstatus":asset["approvalstatus"],"approvaluser":asset["approvaluser"],"approvaldate":asset["approvaldate"][0:10],"totalprice":asset["totalprice"],"guid":asset["guid"],"temp":asset["temp"],"remark":asset["remark"]})
      return HttpResponse(json.dumps({'rows':data_set,'total':length}),content_type='application/json')
    else :
        return HttpResponse(json.dumps({'rows':-1,'total':-1,'role':-1}),content_type='application/json')
@csrf_exempt
def approveuserlist(request):
    userlist=settings.APPROVE_USER_LIST
    return HttpResponse(json.dumps(userlist,ensure_ascii=False),content_type='application/json,charset=utf-8')
    #return HttpResponse(json.dumps(userlist),content_type='application/json')